package m.jclecai.com.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.BitWheelInfo;
import m.jclecai.com.bean.BuyParamBean;
import m.jclecai.com.bean.ItemBean;
import m.jclecai.com.bean.UiClickBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.MyCaiPiaoDialog;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.MyLog;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.RandUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.DltBody;
import m.jclecai.com.view.BitView;
import m.jclecai.com.view.LuckyMenu;

/**
 * Created by ZD on 2017/4/17.
 * 幸运选号
 */

public class LotteryLuckyActivity extends BaseActivity {


    List<ItemBean> beans;
    List<BitWheelInfo> infos;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.llTitle)
    RelativeLayout llTitle;
    @BindView(R.id.lm_menu)
    LuckyMenu lmMenu;
    @BindView(R.id.btView)
    BitView btView;
    @BindView(R.id.iv_start)
    ImageView ivStart;
    @BindView(R.id.llBg)
    RelativeLayout llBg;
    String type = "属相";
    UiClickBean uiClickCache ;
    MyCaiPiaoDialog cpDialog;
    DltBody body;

    @Override
    public int getContentView() {
        return R.layout.activity_lucky;
    }

    @Override
    public void initView() {
        lmMenu = (LuckyMenu) findViewById(R.id.lm_menu);
        btView = (BitView) findViewById(R.id.btView);
        ivStart = (ImageView) findViewById(R.id.iv_start);
    }

    @Override
    public void initData() {
        infos = new ArrayList<>();
        beans = new ArrayList<>();
        btView.setBitInfos(getData(),type);
        uiClickCache = PreferenceUtil.getUiClickCache(this);
        if(uiClickCache.getLshuxiang() != null)
            type = uiClickCache.getLshuxiang().getName();
        lmMenu.setCaiZhong(uiClickCache.getLcaizhong());
        lmMenu.setShuXiang(uiClickCache.getLshuxiang());
        lmMenu.setDuZhu(uiClickCache.getLduzhu());
        showDialog();
        getDltInfo();
        changeUI();
    }

    @Override
    public void initListener() {
        btView.setOnWheelCheckListener(new BitView.OnWheelCheckListener() {
            @Override
            public void onCheck(int position) {
//                DisPlay("选中了" + infos.get(position).text);
            }

            @Override
            public void complete() {
                getNum();
            }
        });
        ivStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btView.startAnimal(btView);
            }
        });
        lmMenu.setMenuClickListener(new LuckyMenu.OnMenuClickListener() {
            @Override
            public void leftButton(final TextView view) {
                showPicker(ACTION.CAIZHONG,view);
            }

            @Override
            public void centerButton(final TextView view) {
                showPicker(ACTION.SHUXIANG,view);
            }

            @Override
            public void rightButton(final TextView view) {
                showPicker(ACTION.DUZHU,view);
            }
        });
    }

    List<ItemBean> getCaizhong() {
        ArrayList<ItemBean> list = new ArrayList<>();
        list.add(new ItemBean(0, "双色球", "ssq" , 6,1,33,16,true,true));
        list.add(new ItemBean(1, "大乐透", "dlt", 5,2,35,12,true,true));
        return list;
    }

    List<ItemBean> getShuxiang() {
        ArrayList<ItemBean> list = new ArrayList<>();
        list.add(new ItemBean(0, "属相", "sx"));
        list.add(new ItemBean(1, "星座", "xz"));
        return list;
    }

    List<ItemBean> getDuZhu() {
        ArrayList<ItemBean> list = new ArrayList<>();
        list.add(new ItemBean(0, "1注", "1"));
        list.add(new ItemBean(1, "2注", "2"));
        list.add(new ItemBean(2, "3注", "3"));
        list.add(new ItemBean(3, "4注", "4"));
        list.add(new ItemBean(4, "5注", "5"));
        list.add(new ItemBean(5, "6注", "6"));
        list.add(new ItemBean(6, "7注", "7"));
        list.add(new ItemBean(7, "8注", "8"));
        list.add(new ItemBean(8, "9注", "9"));
        list.add(new ItemBean(9, "10注", "10"));
        return list;
    }

    //切换ui
    void changeUI(){
        if(type.equals("属相")){
            llBg.setBackgroundResource(R.mipmap.zp_sxbg);
            ivBack.setImageResource(R.mipmap.zp_sxblack);
            StatusBarUtil.setColorNoTranslucent(this,Color.parseColor("#830000"));
        }else{
            llBg.setBackgroundResource(R.mipmap.zp_xzbg);
            ivBack.setImageResource(R.mipmap.zp_xzblack);
            StatusBarUtil.setColorNoTranslucent(this, Color.parseColor("#08203C"));
        }
        btView.setBitInfos(getData(),type);
    }


    List<BitWheelInfo> getData() {
        infos.clear();
        String[] datas;
        if(type.equals("属相")){
            datas = new String[]{"zp_shu", "zp_niu", "zp_hu", "zp_tu", "zp_long", "zp_she",
                    "zp_ma", "zp_yang", "zp_hou", "zp_ji", "zp_gou",
                    "zp_zhu"};
        }else {
            datas = new String[]{"zp_by", "zp_jn", "zp_szi", "zp_jx", "zp_sz", "zp_cn",
                    "zp_tp", "zp_tx", "zp_ss", "zp_mj", "zp_sp"
                    , "zp_sy"};
        }
        for (String data : datas){
            infos.add(new BitWheelInfo(data));
        }
        return infos;
    }

    String luckyNum(){
        String date = "";
        String xz = "[[0, \"3.21-4.20\", \"白羊座\", \"baiyang\"]," +
                " [1, \"4.21-5.21\", \"金牛座\", \"jinniu\"]," +
                " [2, \"5.22-6.21\", \"双子座\", \"shuangzi\"]," +
                " [3, \"6.22-7.22\", \"巨蟹座\", \"juxie\"]," +
                " [4, \"7.23-8.23\", \"狮子座\", \"shizi\"], " +
                "[5, \"8.24-9.23\", \"处女座\", \"chunv\"]," +
                " [6, \"9.24-10.23\", \"天秤座\", \"tianping\"], " +
                "[7, \"10.24-11.22\", \"天蝎座\", \"tianxie\"], " +
                "[8, \"11.23-12.21\", \"射手座\", \"sheshou\"]," +
                " [9, \"12.22-1.20\", \"摩羯座\", \"moxie\"]," +
                " [10, \"1.21-2.19\", \"水瓶座\", \"shuipin\"], " +
                "[11, \"2.20-3.20\", \"双鱼座\", \"shuangyu\"]]";
        JsonArray ja = new Gson().fromJson(xz, JsonArray.class);
        for (int i=0;i<ja.size();i++){
            JsonArray aj = ja.get(i).getAsJsonArray();
            if(i == btView.getCheckPosition()) {
                date = aj.get(1).toString();
                break;
            }
        }
        return date;
    }

    /**
     * 获取大乐透信息
     */
    void getDltInfo() {
        Map<String,String> map = new HashMap<>();
        map.put("type",lmMenu.getCaiZhongValue());
        HttpManager.postAsyn(Constant_Url.DLTTERM, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyLog.i(request.toString());
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                if (!TextUtils.isEmpty(response)) {
                    body = FastOk.get(response,DltBody.class);
                    if(body != null) {
                        tvDate.setVisibility(View.VISIBLE);
                        tvDate.setText(Html.fromHtml(String.format(
                                getString(R.string.sc_caipiao_deadline),
                                body.getTermNo(), body.getStopSaleTime())));
                    }
                }
            }
        },map);
    }

    /**
     * 打开选择器
     * @param flag 标记
     * @param view 设置格式化的时间
     */
    public void showPicker(final ACTION flag,final TextView view){
        //条件选择器
        OptionsPickerView pvOptions = new  OptionsPickerView.Builder(this,
                new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3 ,View v) {
                ItemBean bean = beans.get(options1);
                view.setText(bean.getName());
                switch (flag){
                    case CAIZHONG:
                        lmMenu.setCaiZhong(bean);
                        uiClickCache.setLcaizhong(bean);
                        getDltInfo();
                        break;
                    case SHUXIANG:
                        type = bean.getName();
                        changeUI();
                        lmMenu.setShuXiang(bean);
                        uiClickCache.setLshuxiang(bean);
                        break;
                    case DUZHU:
                        lmMenu.setDuZhu(bean);
                        uiClickCache.setLduzhu(bean);
                        break;
                }
                PreferenceUtil.saveUiClickCache(LotteryLuckyActivity.this,uiClickCache);
            }
        }).setCancelText("取消").setSubmitText("确认").build();
        checkDefaultPicker(pvOptions,flag);
        pvOptions.setPicker(excuData(flag));
        pvOptions.show();
    }

    /**
     * 勾选最后一次的数据
     * @param flag 标记
     */
    void checkDefaultPicker(OptionsPickerView pvOptions,ACTION flag){
        switch (flag) {
            case CAIZHONG:
                if(uiClickCache.getLcaizhong() != null)
                pvOptions.setSelectOptions(uiClickCache.getLcaizhong().getIndex());
                break;
            case SHUXIANG:
                if(uiClickCache.getLshuxiang() != null)
                pvOptions.setSelectOptions(uiClickCache.getLshuxiang().getIndex());
                break;
            case DUZHU:
                if(uiClickCache.getLduzhu() != null)
                pvOptions.setSelectOptions(uiClickCache.getLduzhu().getIndex());
                break;
        }
    }

    /**
     * 处理数据
     * @param flag 标记
     * @return list
     */
    List<ItemBean> excuData(ACTION flag){
        beans.clear();
        switch (flag) {
            case CAIZHONG:
                beans.addAll(getCaizhong());
                break;
            case SHUXIANG:
                beans.addAll(getShuxiang());
                break;
            case DUZHU:
                beans.addAll(getDuZhu());
                break;
        }
        return beans;
    }

    /**
     * 显示摇出的号码
     */
    void getNum(){
        String xzNum = luckyNum();
        final ItemBean cpr = lmMenu.getCaiPiaoRule();
        if(cpr == null) {
            DisPlay("请重新打开页面尝试！");
            return;
        }
        List<List<String>> random = RandUtil.getRandom8(Integer.parseInt(lmMenu.getDuZhuValue()),
                cpr.getRedCount(),
                cpr.getBlueCount(),
                cpr.getRedMaxNum(),
                cpr.getBlueMaxNum(),
                cpr.isType(), cpr.isCanZero(),xzNum);
        cpDialog = new MyCaiPiaoDialog(this,random,cpr.getBlueCount());
        cpDialog.setOnSelectListener(new MyCaiPiaoDialog.onSelectListsner() {
            @Override
            public void again() {
//                btView.startAnimal(btView);
                cpDialog.dismiss();
            }

            @Override
            public void sure(List<List<String>> datas) {
                int money = 2 * datas.size();
                if(lmMenu != null) {
                    final ItemBean cpr = lmMenu.getCaiPiaoRule();
                    BuyParamBean buyParamBean = new BuyParamBean(cpr.getRedCount(), cpr.getBlueCount(), datas);
                    showBuyInfo(buyParamBean.getCodes(), money, datas.size());
                }
            }
        });
        cpDialog.show();
    }

    private void showBuyInfo(String codes,int totalMoney,int multiple) {
        /**
         * 此处提交之前先判断用户是否登录
         */
        Intent intent = new Intent(this, LotteryPayActivity.class);
        intent.putExtra(PAY_VOTENUMS, String.valueOf(multiple));
        intent.putExtra(PAY_MULTIPLE, String.valueOf(1));
        intent.putExtra(PAY_MONEY, String.valueOf(totalMoney));
        intent.putExtra(PAY_CODES, codes);
        intent.putExtra(PAY_TYPE, lmMenu.getCaiZhongValue());
        intent.putExtra(PAY_NAME, "自购");
        intent.putExtra(PAY_NUM, String.valueOf(1));
        if (body != null)
            intent.putExtra(PAY_TERM, BaseUtils.strNoNull(body.getTermNo()));
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    @OnClick(R.id.iv_back)
    protected void close() {
        finish();
    }

    @Override
    protected void onDestroy() {
        if(cpDialog!= null)
            cpDialog.dismiss();
        super.onDestroy();
        if(beans != null)
            beans.clear();
        beans = null;
        if(infos != null)
            infos.clear();
        infos = null;
        System.gc();
    }

    void getParams(){

    }
}
